package com.zoespeer.food_delivery_comment_api.controller;

import com.zoespeer.food_delivery_comment_api.common.ApiResponse;
import com.zoespeer.food_delivery_comment_api.service.FavoriteService;
import com.zoespeer.food_delivery_comment_api.util.TokenParseUtil;
import com.zoespeer.food_delivery_comment_api.vo.AddFavoriteVO;
import com.zoespeer.food_delivery_comment_api.vo.CancelLikeRequestVO;
import com.zoespeer.food_delivery_comment_api.vo.FavoriteVO;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/favorite")
public class FavoriteController {

    @Autowired
    private FavoriteService favoriteService;

    @GetMapping("/getMyLike")
    public ApiResponse<List<FavoriteVO>> getMyLike(
            @RequestParam("userId") String userId // 从请求参数接收userId
    ) {
        // 校验userId合法性（非空、格式等）
        if (userId == null || userId.trim().isEmpty()) {
            return ApiResponse.error("用户ID不能为空");
        }

        try {
            List<FavoriteVO> favorites = favoriteService.getMyLike(userId);
            return ApiResponse.success(favorites, "查询我的收藏成功");
        } catch (RuntimeException e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    // 新增：取消收藏接口
    @DeleteMapping("/cancelLike")
    public ApiResponse<Object> cancelLike(
            @RequestHeader("Authorization") String token, // Header传Authorization
            @Valid @RequestBody CancelLikeRequestVO request // Body传userId和canteenId
    ) {
        // 1. 解析Token，校验当前用户身份（确保请求的userId与Token一致，防止越权）
        var tokenUserIdResp = TokenParseUtil.parseUserIdAsInt(token);
        if (tokenUserIdResp.getCode() != 200) {
            return ApiResponse.error(tokenUserIdResp.getMessage());
        }
        Integer tokenUserId = tokenUserIdResp.getData();

        // 2. 校验请求中的userId与Token中的userId一致（防止越权取消他人收藏）
        if (!tokenUserId.toString().equals(request.getUserId())) {
            return ApiResponse.error("无权取消他人收藏，请求userId与Token不一致");
        }

        // 3. 调用Service执行取消收藏
        try {
            favoriteService.cancelLike(request);
            return ApiResponse.success(null, "取消收藏成功");
        } catch (RuntimeException e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    @PostMapping("/addLike")
    public ApiResponse<Void> addLike(
            @RequestHeader("Authorization") String token,
            @Valid @RequestBody AddFavoriteVO request
    ) {
        // 1. 解析Token，校验当前用户身份（复用 cancelLike 用的 TokenParseUtil，保持一致）
        var tokenUserIdResp = TokenParseUtil.parseUserIdAsInt(token);
        if (tokenUserIdResp.getCode() != 200) {
            return ApiResponse.error(tokenUserIdResp.getMessage());
        }
        Integer tokenUserId = tokenUserIdResp.getData();

        // 2. 校验请求中的userId与Token中的userId一致（防止越权收藏他人账号）
        // 注意：AddFavoriteVO 的 userId 是 String 类型，需转 Integer 对比（与 cancelLike 逻辑对齐）
        Integer requestUserId;
        try {
            requestUserId = Integer.parseInt(request.getUserId());
        } catch (NumberFormatException e) {
            return ApiResponse.error("用户ID格式错误，必须是数字");
        }
        if (!tokenUserId.equals(requestUserId)) {
            return ApiResponse.error("无权为他人收藏，请求userId与Token不一致");
        }

        // 3. 调用Service执行添加收藏（异常捕获与返回格式和 cancelLike 一致）
        try {
            favoriteService.addLike(request);
            return ApiResponse.success("收藏餐厅成功");
        } catch (RuntimeException e) {
            return ApiResponse.error(e.getMessage());
        }
    }
}